package com.gitee.ywj1352.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.function.Function;

/**
 * 对象池,
 * 当pool 中初始化了 5个对象 所以的线程在使用的时候只能出现这
 * 五个对象
 *
 * @param <T>
 * @param <R>
 */
public class ObjPool<T, R> {

    private List<T> pool = new ArrayList<>();

    private Semaphore sem;

    public ObjPool(int size, T t) {
        sem = new Semaphore(size);
        for (int i = 0; i < size; i++) {
            pool.add(t);
        }
    }

    //执行的方法
    public R doExecute(Function<T, R> fun) {
        T executor = null;
        try {
            sem.acquire();
            Thread.sleep(1000);
            executor = pool.remove(0);
            return fun.apply(executor);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            pool.add(executor);
            sem.release();
        }
        return null;
    }

    public static void main(String[] args) {
        ObjPool pool = new ObjPool(10, 2);
        for (int i = 0; i < 15; i++) {
            new Thread(() -> {
                pool.doExecute(t -> {
                    System.out.println(t);
                    return t.toString();
                });
            }).start();
        }
    }
}
